import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import db.DatabaseConnector;

public class ListQuestionCategories extends HttpServlet {
    
//This subroutine is called by ListQuestions.jsp (admin page)
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        // Variables for the database connection
        DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        DatabaseConnector subCatCon = null;
        ResultSet rs = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
	    //Returns question categories in order
            String SQL = "SELECT CatID,DisplayOrder,CategoryName FROM QuestionCategories WHERE SubCatNum = 0 ORDER BY DisplayOrder";
            rs = con.selectSQL_RS(SQL);

            // Print the categories
            if(rs != null)
            {
                while(rs.next()) {
                    String catID = rs.getString("CatID");
                    int dOrder = rs.getInt("DisplayOrder");
                    String catName = rs.getString("CategoryName");
                
                    out.println("<div id=\"" + catID + "_" + dOrder + "\">");
                    out.print("<div id=\"" + catID + "_cat_" + dOrder +  "\"" );
                    out.println("onClick=\"setHighlight(this);\" onDblClick=\"showCategoryField(this)\">");
                    out.print("<img id=\"" + catID + "_img\" onClick=\"toggleViewChildren(this);\" ");
                    out.print("align=\"absmiddle\" vspace=\"6\" hspace=\"6\" src=\"../img/");

                    subCatCon = new DatabaseConnector(DatabaseConnector.getDatabaseType());
                    boolean hasSubCats = hasSubCategories(catID, subCatCon);
                
                    if(hasSubCats) {
                        out.println("plus.gif\"/>");
                    } else {
                        out.println("nochild.gif\"/>");
                    }
                
                    out.println("<span id=\"" + catID + "_text\">" + catName + "</span>");
                    out.print("<input id=\"" + catID + "_field_" + dOrder + "\" " +
                        "name=\"" + catID + "_field_" + dOrder + "\" size=\"40\" ");
                    out.print("style=\"display: none;\" onBlur=\"hideCategoryField(this);\" ");
                    out.println("value=\"" + catName + "\"/>");
                    out.println("</div>");
                
                    if(hasSubCats) {
                        out.println("<div id=\"" + catID + "_subcats\" style=\"display: none;\">");
                        out.println(printSubCategories(catID, subCatCon));
                        out.println("</div>");
                    }
                    out.println("</div>");
                }
            }
        } catch (SQLException e) {
            out.println("SQLException caught in ListQuestionCategories, doGet(): " + e.getMessage());
        } finally {
            try {
                if(rs != null) rs.close();
                con.CleanUp();
                subCatCon.CleanUp();
            } catch (Exception ignored) {}
        }
    }
    
    private boolean hasSubCategories(String catID, DatabaseConnector conn) {
        String SQL = "SELECT CatID FROM QuestionCategories WHERE TopLevelNum = ? AND SubCatNum > ? ";
        String[][] r = conn.selectSQL(SQL,1,new Object[]{catID,0});

        try {
            if (r[0][0].equals("null")){ } //just to trigger catch if r[0][0] doesn't exist
                return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    private String printSubCategories(String cID, DatabaseConnector conn) {
        String s = "";
        String catID;
        String catName;
        int dOrder;

        ResultSet rs = null;

        try {
        //Returns subcategories in number order
        String SQL = "SELECT CatID,DisplayOrder,CategoryName FROM QuestionCategories WHERE TopLevelNum = ? AND SubCatNum > 0 ORDER BY SubCatNum";
        rs = conn.selectSQL_RS(SQL, new Object[]{cID});

        if(rs != null)
        {
            while(rs.next()) {
                catID = rs.getString("CatID");
                dOrder = rs.getInt("DisplayOrder");
                catName = rs.getString("CategoryName");
                
                s += "<div id=\"" + catID + "_cat_" + dOrder + "\" onClick=\"setHighlight(this);\" onDblClick=\"showCategoryField(this)\">\n";
                s += "<img id=\"" + catID + "_img\" onClick=\"toggleViewChildren(this);\" ";
                s += "align=\"absmiddle\" vspace=\"6\" hspace=\"12\" src=\"../img/nochild.gif\">\n";
                s += "<span id=\"" + catID + "_text\">" + catName + "</span>\n";
                s += "<input id=\"" + catID + "_field_" + dOrder + "\" name=\"" + catID + "_field_" + dOrder + "\" size=\"40\" ";
                s += "style=\"display: none;\" onBlur=\"hideCategoryField(this);\" ";
                s += "value=\"" + catName + "\"/>\n";
                s += "</div>\n\n";
            }
        }
        } catch (SQLException e) {
            System.out.println("SQLException caught in ListQuestionCategories, printSubCategories(): " + e.getMessage());
        } finally {
            try {
                rs.close();
            } catch (Exception ignored) {}
        }
        return s;
    }
}
